import {Component, OnInit, ViewChild} from '@angular/core';
import {adSystemApiUrl} from '../../../../config/api';
import {HttpService} from '../../../lib/service/http.service';
import {ModalDirective} from 'ngx-bootstrap';

export class AddTemp {
  wx_id;
  title;
  keyword_list = '';
}

export class EditTemp {
  id;
  wx_id;
  title;
  keyword_list = {};
}

@Component({
  selector: 'app-template',
  templateUrl: 'template.component.html',
  styleUrls: ['template.component.scss'],
})

export class TemplateComponent implements OnInit {

  loadingShow = false;
  keyword = '';
  templateList = [];
  operateId;
  id;  // 关键词ID
  key;  // 关键词
  keyList = [];

  type: string;
  message: string;
  isShow = false;
  totalItems: number;
  itemsPerPage = 12;
  currentPage;

  addTemp = new AddTemp();
  editTemp = new EditTemp();

  @ViewChild('deleteModal') public deleteModal: ModalDirective;
  @ViewChild('addTempModal') public addTempModal: ModalDirective;
  @ViewChild('editTempModal') public editTempModal: ModalDirective;

  constructor(private httpService: HttpService) {
  }

  ngOnInit() {
    this.getTemplateList(1, this.itemsPerPage, '')
  }

  // 获取模板消息列表
  getTemplateList(page, pageSize, keyword) {
    const url = `${adSystemApiUrl}/v1/admin/wxxcx_template_message/list?page=${page}&pageSize=${pageSize}&keyword=${keyword}`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.currentPage = res.data.current_page;
        this.totalItems = res.data.total;
        this.templateList = res.data.data;
        this.templateList.every((val, idx, array) => {
          val.key_list = JSON.parse(val.key_list);
          val.keyword_list = JSON.parse(val.keyword_list);
          return true;
        })
      }
    )
  }

  // 删除弹框
  delTemp(id: number) {
    this.operateId = id;
    this.deleteModal.show();
  }

  delTempSubmit() {
    const url = `${adSystemApiUrl}/v1/admin/wxxcx_template_message/del?id=${this.operateId}`;
    return this.httpService.httpPostAuth(url, '').subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '删除成功';
          this.isShow = true;
          this.deleteModal.hide();
          this.getTemplateList(1, this.itemsPerPage, this.keyword);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 添加关键词
  addKeyWord() {
    if (!!this.id && !!this.key) {
      if (!this.keyList.length) {
        this.keyList.push({id: this.id, key: this.key});
        this.id = null;
        this.key = '';
      } else {
        let canAdd = true;
        this.keyList.every((val, idx, array) => {
          if (val.id === this.id) {
            canAdd = false;
            return false;
          } else {
            return true;
          }
        });
        if (canAdd) {
          this.keyList.push({id: this.id, key: this.key});
          this.id = null;
          this.key = '';
        }
      }
    } else {
      return;
    }
  }

  // 新增消息模板
  addTempSubmit() {
    this.addTemp.keyword_list = '';
     for (let i =0;i < this.keyList.length; i++) {
       if (i === 0) {
         this.addTemp.keyword_list = '"' + this.keyList[i].id.toString() + '"' +':' + '"'+this.keyList[i].key+'"';
       } else {
         const addData = ',' + '"' + this.keyList[i].id.toString() + '"' +':' + '"'+this.keyList[i].key+'"';
         this.addTemp.keyword_list = this.addTemp.keyword_list + addData;
       }
     }
    this.addTemp.keyword_list = '{'+this.addTemp.keyword_list+'}';
    const url = `${adSystemApiUrl}/v1/admin/wxxcx_template_message/add`;
    return this.httpService.httpPostAuth(url, this.addTemp).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '消息模板添加成功';
          this.isShow = true;
          this.getTemplateList(1, this.itemsPerPage, this.keyword);
          this.addTempModal.hide();
          this.addTemp.wx_id = null;
          this.addTemp.title = null;
          this.keyList = [];
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    )
  }

  // 编辑消息模板
  editTempDialog(data) {
    this.editTemp.id = data.id;
    this.editTemp.wx_id = data.wx_id;
    this.editTemp.title = data.title;
    const len = data.keyword_list.length;
    this.keyList = [];
    for (let i = 0; i < len; i++) {
      this.keyList.push({id: data.key_list[i], key: data.keyword_list[i]});
    }
    this.editTempModal.show();
  }

  editTempSubmit() {
    this.editTemp.keyword_list = '';
    for (let i =0;i < this.keyList.length; i++) {
      if (i === 0) {
        this.editTemp.keyword_list = '"' + this.keyList[i].id.toString() + '"' +':' + '"'+this.keyList[i].key+'"';
      } else {
        const addData = ',' + '"' + this.keyList[i].id.toString() + '"' +':' + '"'+this.keyList[i].key+'"';
        this.editTemp.keyword_list = this.editTemp.keyword_list + addData;
      }
    }
    this.editTemp.keyword_list = '{'+this.editTemp.keyword_list+'}';
    const url = `${adSystemApiUrl}/v1/admin/wxxcx_template_message/mod`;
    return this.httpService.httpPostAuth(url, this.editTemp).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '消息模板修改成功';
          this.isShow = true;
          this.getTemplateList(1, this.itemsPerPage, this.keyword);
          this.editTempModal.hide();
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    )
  }

  // 搜索
  search() {
    this.getTemplateList(1, this.itemsPerPage, this.keyword);
  }

  reset() {
    this.keyword = '';
    this.getTemplateList(1, this.itemsPerPage, this.keyword);
  }

  pageChanged(event: any): void {
    window.scrollTo(0,0);
    this.getTemplateList(event.page, this.itemsPerPage, this.keyword);
  }

}
